/**
 * @Description: 订单管理相关API
 * @Author: lujq
 * @Date: 2025-01-04
 * @LastEditors: lujq
 * @LastEditTime: 2025-01-04 10:55:00
 */

import { http } from './index'
import type { Order, PageResponse, PageParams, OrderStatistics } from '@/types'

/**
 * 获取订单列表
 * @param params 查询参数
 * @returns 订单列表
 */
export const getOrderList = async (
  params: PageParams & {
    keyword?: string
    status?: string
    paymentStatus?: string
    customerId?: string
    dateRange?: [string, string]
  },
) => {
  try {
    // 构建查询URL，包含分页和过滤参数
    const queryParams = new URLSearchParams()
    queryParams.append('page', params.page.toString())
    queryParams.append('pageSize', params.pageSize.toString())
    
    if (params.keyword) queryParams.append('keyword', params.keyword)
    if (params.status) queryParams.append('status', params.status)
    if (params.paymentStatus) queryParams.append('paymentStatus', params.paymentStatus)
    if (params.customerId) queryParams.append('customerId', params.customerId)
    if (params.dateRange) {
      queryParams.append('startDate', params.dateRange[0])
      queryParams.append('endDate', params.dateRange[1])
    }
    
    const response = await http.get<{
      items: Order[]
      total: number
      page: number
      pageSize: number
      totalPages: number
    }>(`/orders?${queryParams.toString()}`)
    
    // 转换为前端期望的格式
    return {
      ...response,
      data: {
        list: response.data.items,
        total: response.data.total,
        page: response.data.page,
        pageSize: response.data.pageSize
      }
    }
  } catch (error) {
    console.error('订单API调用失败:', error)
    throw error
  }
}

/**
 * 获取订单详情
 * @param id 订单ID
 * @returns 订单详情
 */
export const getOrderDetail = (id: string) => {
  return http.get<Order>(`/orders/${id}`)
}

/**
 * 创建订单
 * @param data 订单数据
 * @returns 创建结果
 */
export const createOrder = (data: Omit<Order, 'id' | 'orderNo' | 'createTime' | 'updateTime'>) => {
  const orderNo = `ORD${Date.now()}`
  return http.post<Order>('/orders', {
    ...data,
    id: Date.now().toString(),
    orderNo,
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString(),
  })
}

/**
 * 更新订单
 * @param id 订单ID
 * @param data 订单数据
 * @returns 更新结果
 */
export const updateOrder = (id: string, data: Partial<Order>) => {
  return http.put<Order>(`/orders/${id}`, {
    ...data,
    updateTime: new Date().toISOString(),
  })
}

/**
 * 删除订单
 * @param id 订单ID
 * @returns 删除结果
 */
export const deleteOrder = (id: string) => {
  return http.delete(`/orders/${id}`)
}

/**
 * 更新订单状态
 * @param id 订单ID
 * @param status 新状态
 * @returns 更新结果
 */
export const updateOrderStatus = (id: string, status: string) => {
  return http.patch(`/orders/${id}`, {
    status,
    updateTime: new Date().toISOString(),
  })
}

/**
 * 更新支付状态
 * @param id 订单ID
 * @param paymentStatus 支付状态
 * @returns 更新结果
 */
export const updatePaymentStatus = (id: string, paymentStatus: string) => {
  return http.patch(`/orders/${id}`, {
    paymentStatus,
    updateTime: new Date().toISOString(),
  })
}

/**
 * 获取订单统计数据
 * @returns 订单统计数据
 */
export const getOrderStatistics = () => {
  return http.get<OrderStatistics>('/analytics/orders')
}

/**
 * 获取逾期订单
 * @returns 逾期订单列表
 */
export const getOverdueOrders = () => {
  return http.get<Order[]>('/orders/overdue')
}

/**
 * 导出订单数据
 * @param params 查询参数
 * @returns 导出文件
 */
export const exportOrders = (params: any) => {
  return http.get('/orders/export', {
    params,
    responseType: 'blob',
  })
}
